package main

import (
	"fmt"
	"math/rand"
	"sort"
	"time"
)

type student struct {
	name string
	age  int
}

func main() {
	//定义
	//map[keyType]valueType 使用make

	m := make(map[string]*student)
	stus := []student{
		{name: "aa", age: 18},
		{name: "bb", age: 19},
		{name: "cc", age: 20},
	}
	for _, v := range stus {
		//fmt.Println(v)
		c := v
		m[v.name] = &c
	}
	//fmt.Println(m)
	for k, v := range m {
		fmt.Println(k, "=>", v)

	}
	return

	scoreMap := make(map[string]int, 8)
	scoreMap["张三"] = 90
	scoreMap["李四"] = 70
	fmt.Println(scoreMap)
	//判断某个key是否存在
	if value, ok := scoreMap["王五"]; ok {
		fmt.Println("has value ", value)
	} else {
		fmt.Println("has not value")
	}
	delete(scoreMap, "张三")
	fmt.Println(scoreMap)
	sortMap()
	mapSlice()
	sliceMap()
}

// 值为切片类型的map
func sliceMap() {
	var sliceMap = make(map[string][]string, 3)
	fmt.Println(sliceMap)
	fmt.Println("after init")
	key := "中国"
	v, ok := sliceMap[key]
	if !ok {
		v = make([]string, 0, 2)
	}
	v = append(v, "上海", "北京")
	sliceMap[key] = v
	fmt.Println(sliceMap)
}

// 元素为map类型的切片
func mapSlice() {
	var mapSlice = make([]map[string]string, 3)
	for i, v := range mapSlice {
		fmt.Printf("index:%d value:%v\n", i, v)
	}
	fmt.Printf("after init")
	//对切片中的map元素进行初始化
	mapSlice[0] = make(map[string]string, 10)
	mapSlice[0]["name"] = "小王子"
	mapSlice[0]["password"] = "123456"
	mapSlice[0]["address"] = "沙河"
	for i, v := range mapSlice {
		fmt.Printf("i: %d, v: %v\n", i, v)
	}
}

// 按照指定顺序遍历map
func sortMap() {
	rand.Seed(time.Now().UnixNano())
	var scoreMap = make(map[string]int, 200)
	for i := 0; i < 100; i++ {
		key := fmt.Sprintf("stu%02d", i) //生成stu开头的字符串
		value := rand.Intn(100)          //生成随机数
		scoreMap[key] = value
	}
	//取出map中的所有key存入到切片keys
	var keys = make([]string, 0, 200)
	for key := range scoreMap {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	for _, key := range keys {
		fmt.Println(key, scoreMap[key])
	}
}
